import axios from 'axios';
// import proxy from '../configs/host';
import { getEndian } from 'utils/path';

const env = import.meta.env.MODE || 'development';
console.log('aaaa:', env);
// const API_HOST = proxy[env].API;

const SUCCESS_CODE = 'OK';
const TIMEOUT = 60000;

export const instance = axios.create({
  baseURL: 'https://0dac-120-231-178-84.ngrok-free.app',
  timeout: TIMEOUT,
  withCredentials: true,
  headers: {
    // token: 'admin_for_test_asdasd',
    'Content-Type': 'application/json',
    token: `Bearer ${localStorage.getItem('ai_transport_token')}`,
  },
});

// 请求拦截器：校验参数类型
instance.interceptors.request.use((config) => {
  if (config.params && 'page' in config.params) {
    config.params.page = Math.max(1, config.params.page);
  }
  return config;
});

// 响应拦截器：统一解析错误
instance.interceptors.response.use(
  (res) => res.data,
  (error) => {
    if (error.response?.status === 422) {
      // 解析并抛出后端校验错误
      throw new Error(`参数错误：${JSON.stringify(error.response.data.errors)}`);
    }
    throw error;
  }
);

instance.interceptors.response.use(
  // eslint-disable-next-line consistent-return
  (response) => {
    console.log("响应数据: ", response);
    if (response.status === 200) {
      const { data } = response;
      if (data.code === SUCCESS_CODE || data.code === 200) {
        return data;
      }
      return Promise.reject(data);
    }
    return Promise.reject(response?.data);
  },
  (e) => {
    // console.log("error:", e, location.pathname, location.pathname.length);
    const lpath = location.pathname.split('/').pop();
    if (location.pathname.length > 1) {
      if(e?.status === 401 && (!['login', 'register', 'reset_password'].includes(lpath))) {
        const endianMap = {'用户': 'client', '平台': 'platform'}
        location.href = `/${endianMap[getEndian()]}/login`;
      }
    }

    Promise.reject(e);
  },
);

export default instance;
